import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/gestures.dart';
import 'package:lcapp/api/interface/login_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/local_info.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/user_data_entity.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/toast/toast.dart';

bool isLogin = false;
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  var phoneController =  TextEditingController();
  var codeController =  TextEditingController();
  late Timer _countdownTimer; // 计时器
  bool isSendCode = false; // 是否发送了验证码 正在等待
  bool isCheck = false; // 是否已读协议
  String codeText = '获取验证码';
  int _countdownNum = 59; // 倒计时秒数
  String get phone => phoneController.text;
  String get code => codeController.text;
  bool isBack = false;
  @override
  void initState() {
    super.initState();
    isLogin = true;
  }


  @override
  void dispose() {
    isLogin = false;
    phoneController?.dispose();
    codeController?.dispose();
    _countdownTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            // 触摸收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              GestureDetector(
                onTap: (){
                  Navigator.of(context).pop();
                },
                child: Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(top: 150.w),
                  child: const Icon(Icons.arrow_back_ios_outlined,size: 30,color: Colors.black,),
                ),
              ),
              Container(
                width: double.infinity,
                margin: EdgeInsets.only(top: 50.w),
                child:  Text('短信验证码登录',style: TextStyle(
                    color: Colors.black,
                    fontSize: 36.sp,
                    fontWeight: FontWeight.bold
                ),),
              ),
              Container(
                margin: EdgeInsets.only(top: 20.w),
                width: double.infinity,
                child:  Text('未注册手机号验证后将自动注册',style: TextStyle(
                  color: const Color(0xffAEAEAE),
                  fontSize: 26.sp,
                ),),
              ),
              Container(
                margin: EdgeInsets.only(top: 15.w),
                height: 88.w,
                child: TextField(
                  controller: phoneController,
                  textInputAction: TextInputAction.done,
                  maxLength: 11,
                  maxLines: 1,
                  // cursorColor: Color(0xFFFF3000),
                  keyboardType: TextInputType.number,
                  autocorrect: true,
                  autofocus: false,
                  decoration:  InputDecoration(
                    contentPadding: EdgeInsets.only(left: 17.w),
                    hintText: "请输入手机号",
                    hintStyle: TextStyle(
                      color: const Color(0xFFAEAEAE),
                      fontSize: 26.sp,
                      fontWeight: FontWeight.w500,
                    ),
                    counterText: "",
                    border: const OutlineInputBorder(
                      borderSide: BorderSide.none,
                    ),
                    fillColor: const Color(0xFFF8F8F8),
                    filled: true,
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 15.w),
                height: 88.w,
                child: Stack(
                  children: [
                    Container(
                      child: TextField(
                        controller: codeController,
                        textInputAction: TextInputAction.done,
                        maxLength: 6,
                        maxLines: 1,
                        keyboardType: TextInputType.number,
                        autocorrect: true,
                        autofocus: false,
                        cursorColor: Color(0xFFFF3000),
                        decoration:  InputDecoration(
                          contentPadding: EdgeInsets.only(left: 17.w),
                          hintText: "请输入验证码",
                          hintStyle: TextStyle(
                            color: Color(0xFFAAAAAA),
                            fontSize: 26.sp,
                            fontWeight: FontWeight.w500,
                          ),
                          counterText: "",
                          border: OutlineInputBorder(
                            borderSide: BorderSide.none,
                          ),
                          fillColor: Color(0xFFF8F8F8),
                          filled: true,
                        ),
                      ),
                    ),
                    Positioned(
                      right: 40.w,
                      top: 20.w,
                      child: GestureDetector(
                        onTap: isSendCode ? null : () => getCode(),
                        child: Container(
                          alignment: Alignment.center,
                          child: Text(
                            '$codeText',
                            style: TextStyle(
                                fontSize: 26.sp,
                                color: isSendCode
                                    ? Color(0xFF999999)
                                    : Color(0xFFFA6E28)),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              GestureDetector(
                onTap: (){
                  login();
                },
                child: Container(
                  height: 88.w,
                  width: double.infinity,
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(top: 30.w),
                  decoration: BoxDecoration(
                    color: const Color(0xffFA6E28), // 渐变色
                    borderRadius: BorderRadius.circular(6.w),
                  ),
                  child: Text(
                    '登录',
                    style: TextStyle(
                        color: Colors.white, fontSize: 30.sp),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 15.w),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          isCheck = !isCheck;
                        });
                      },
                      child: Container(
                        color: Colors.transparent,
                        width: 50.w,
                        padding: EdgeInsets.only(top: 20.w,bottom: 20.w),
                        // margin: EdgeInsets.only(right: 8.w),
                        child: Icon(
                          isCheck
                              ? Icons.check_circle
                              : Icons.panorama_fish_eye,
                          size: 30.w,
                          color:
                          isCheck ? Color(0xffFA6E28) : Colors.grey,
                        ),
                      ),
                    ),
                    Expanded(child:  RichText(
                      maxLines: 2,
                      softWrap: true,
                      text: TextSpan(
                        text: '我已阅读并同意以下协议',
                        style: TextStyle(
                          fontSize: 24.w,
                          color: const Color(0xff999999),
                        ),
                        children: <TextSpan>[
                          TextSpan(
                            text: '《用户协议》',
                            style:  TextStyle(
                              color: const Color(0xff224D79),
                              fontSize: 24.w,
                            ),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                Navigator.of(context).pushNamed('H5Page',arguments: {
                                  'url':protocolURL,
                                  'title':'《用户协议》'
                                });
                              },
                          ),
                          TextSpan(
                            text: '和',
                            style: TextStyle(
                              fontSize: 24.w,
                              color: const Color(0xff999999),
                            ),),
                          TextSpan(
                            text: '《隐私协议》',
                            style: TextStyle(
                              color: const Color(0xff224D79),
                              fontSize: 24.w,
                            ),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () async {
                                Navigator.of(context).pushNamed('H5Page',arguments: {
                                  'url':privacyURL,
                                  'title':'《隐私协议》'
                                });
                              },
                          ),
                        ],
                      ),
                      textAlign: TextAlign.left,
                    ),)
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 开始倒计时
  startCountDownTimer() {
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownNum > 0) {
          codeText = "等待 ${_countdownNum--}s";
        } else {
          isSendCode = false;
          if(_countdownTimer!=null){
            _countdownTimer.cancel();
          }
          _countdownNum = 59;
          codeText = '获取验证码';
        }
      });
    });
  }

  // 获取验证码
  getCode() async {
    if (phone.isEmpty) {
      showToast("手机号不能输入为空");
      return;
    }
    if (phone.length < 11) {
      showToast("请输入正确的手机号");
      return;
    }

    ResponseData res = await LoginAPI.getPhoneCode(phone);
    if(res.code==200){
      setState(() {
        showToast("验证码已发送");
        isSendCode = true;
        codeText = "等待 60s";
      });
      startCountDownTimer();
    }

  }

  // 点击登陆
  login() async {
    if (phone.trim().isEmpty) {
      showToast("手机号不能输入为空");
      return;
    }
    if (phone.trim().length < 11) {
      showToast("请输入正确的手机号");
      return;
    }
    if (code.trim().isEmpty) {
      showToast("验证码不能为空");
      return;
    }
    if (!isCheck) {
      showToast("请先勾选用户协议与隐私政策");
      return;
    }
    showLoading();
    ResponseData res = await LoginAPI.login(phone, code);
    hideLoading();
    if(res.code==200&&res.data!=null){
      showToast('登录成功');
      AsrLocalInfo.setToken(res.data['token']);
      AsrLocalInfo.setUserId(res.data['id']);
      await refreshUserInfo();
      if(userInfo.userstate == 0){
        Navigator.of(context).popAndPushNamed("ReginPage");
      }else{
        Navigator.of(context).pop();
        eventBus.fire(LoginState());
      }

    }


  }


}
